package com.message.api.user.controller;

import com.base.annotation.SysLog;
import com.base.annotation.Unsecured;
import com.base.context.Context;
import com.base.context.ContextHolder;
import com.base.context.ContextImpl;
import com.base.helper.Result;
import com.base.helper.StringUtils;
import com.base.helper.UserKeyUtils;
import com.message.api.base.entity.AcConfig;
import com.message.api.base.service.AcConfigService;
import com.message.api.group.entity.AcGroup;
import com.message.api.group.service.AcActionPageService;
import com.message.api.group.service.AcGroupService;
import com.message.api.user.entity.AcUser;
import com.message.api.user.service.AcLoginlogService;
import com.message.api.user.service.AcUserService;
import com.message.api.user.service.SsoService;
import com.message.api.user.vo.AcUserVo;
import com.message.api.user.vo.LoginSuccessVo;
import com.message.api.user.vo.LoginVo;
import com.message.api.user.vo.SsoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @Author mzl.
 */
@Api(tags = "sso登录")
@RestController
@RequestMapping("/sso")
public class SsoController {

    private static final Logger              LOG = LoggerFactory.getLogger(SsoController.class);
    @Autowired
    private              AcGroupService      acGroupService;
    @Autowired
    private              AcUserService       acUserService;
    @Autowired
    private              AcConfigService     acConfigService;
    @Autowired
    private              AcActionPageService acActionPageService;
    @Autowired
    private              SsoService          ssoService;
    @Autowired
    private              AcLoginlogService   acLoginlogService;

    /**
     * 验证登录令牌是否有效
     *
     * @param sso
     * @return
     */
    private boolean verifyKey(SsoVo sso) {
        AcConfig acConfig = acConfigService.findByConfigname("ssokey");
        if (null == acConfig) {
            throw new RuntimeException("没有找到密钥");
        }
        if (UserKeyUtils.isTimeOut(sso.getT())) {
            throw new RuntimeException("当前请求令牌已超时");
        }
        String uk = UserKeyUtils.encode(sso.getTeacherid(), sso.getT(), acConfig.getConfigvalue());
        if (StringUtils.isEquals(uk, sso.getUserkey())) {
            return true;
        }
        return false;
    }

    /**
     * 添加登录信息
     *
     * @param context
     * @param user
     * @return
     */
    private LoginSuccessVo normalizeContext(Context context, AcUser user) {
        AcGroup  acGroup = acGroupService.getById(user.getAcgroup());
        AcUserVo vo      = new AcUserVo(user, acGroup.getGrouptypeid() + "", acGroup.getAcgroup());
        Context  ctx     = ContextHolder.isOnline(vo, AcUserVo.class);
        if (null != ctx && !StringUtils.isEquals(ctx.currentToken(), context.currentToken())) {
            ContextHolder.remove(ctx.currentToken());
        }
        context.asUser(vo);
        List<String> accessUris = acActionPageService.findByGroupid(acGroup.getId());
        if (null != accessUris && accessUris.size() > 0) {
            context.asAccessUris(accessUris);
        }
        user.setPassword(null);
        return new LoginSuccessVo(user, context.currentToken());
    }

    /**
     * 获取 ticket
     *
     * @param ticket
     * @return
     */
    @SysLog(action = "ssoLogin", value = "单点登录")
    @ApiOperation(value = "单点登录")
    @RequestMapping(value = "/getTicket", method = RequestMethod.GET)
    @Unsecured
    public Result<LoginSuccessVo> getTicket(@RequestParam("ticket") String ticket) {
        Context context = ContextHolder.currentContext();
        if(ticket != null){
            String teacherId = ssoService.getUserContext(ticket); // 获取用户上下文（教师工号）
            AcUser acUser = acUserService.findByTeacherNumber(teacherId); // 根据上下文获取用户信息
            String accessToken = ssoService.getAccessToken();
            if(acUser != null && accessToken != null && "1".equals(acUser.getEnable())){
                acLoginlogService.addLog(acUser.getId(), acUser.getUsername(), "t", null);
                return new Result<>(true, normalizeContext(context, acUser));
            }
        }
        acLoginlogService.addLog(null, null, "f", "该账号不存在");
        return new Result(false, "该账号不存在，请重新登录", "该账号不存在，请重新登录");
    }

//    /**
//     * 获取 ticket
//     *
//     * @param ticket
//     * @return
//     */
//    @SysLog(action = "ssoLogin", value = "单点登录")
//    @ApiOperation(value = "单点登录")
//    @RequestMapping(value = "/getTicket", method = RequestMethod.GET)
//    @Unsecured
//    public RedirectView getTicket(@RequestParam("ticket") String ticket) {
//        if(ticket != null){
//            String teacherId = ssoService.getUserContext(ticket); // 获取用户上下文（教师工号）
//            AcUser acUser = acUserService.findByTeacherNumber(teacherId); // 根据上下文获取用户信息
//            String accessToken = ssoService.getAccessToken();
//            if(acUser != null && accessToken != null){
////                String redirectUrl = "https://mp.gcu.edu.cn/mgr/explain";
//                String redirectUrl = "http://localhost:8091/mgr/explain";
//                // 创建RedirectView并设置重定向URL
//                RedirectView redirectView = new RedirectView(redirectUrl);
//                redirectView.setStatusCode(HttpStatus.FOUND);  // 使用302状态码进行重定向
//                redirectView.setExposeModelAttributes(false); // 禁止将Model中的属性添加到URL参数
//                return redirectView;
//            }
//        }
////        String loginUrl = "https://mp.gcu.edu.cn/login";
//        String loginUrl = "http://localhost:8091/login";
//        return new RedirectView(loginUrl);
//    }

//    /**
//     * 获取 ticket
//     *
//     * @param ticket
//     * @return
//     */
//    @SysLog(action = "ssoLogin", value = "单点登录")
//    @ApiOperation(value = "单点登录")
//    @RequestMapping(value = "/getTicket", method = RequestMethod.GET)
//    @Unsecured
//    public ResponseEntity<Void> getTicket(@RequestParam("ticket") String ticket) throws URISyntaxException {
//        HttpHeaders headers = new HttpHeaders();
//        if(ticket != null){
//            String teacherId = ssoService.getUserContext(ticket); // 获取用户上下文（教师工号）
//            AcUser acUser = acUserService.findByTeacherNumber(teacherId); // 根据上下文获取用户信息
//            String accessToken = ssoService.getAccessToken();
//            if(acUser != null && accessToken != null){
////                String redirectUrl = "https://mp.gcu.edu.cn/mgr/explain";
////                URI redirectUrl = new URI("http://localhost:8091/mgr/explain"); // 设置重定向的目标URL
//                URI redirectUrl = new URI("www.baidu.com");
//                headers.setLocation(redirectUrl); // 设置重定向的目标URL
//                return new ResponseEntity<>(headers, HttpStatus.FOUND); // 返回302状态码
//            }
//        }
////        String loginUrl = "https://mp.gcu.edu.cn/login";
//        URI loginUrl = new URI("http://localhost:8091/login"); // 设置重定向的目标URL
//        headers.setLocation(loginUrl); // 设置重定向的目标URL
//        return new ResponseEntity<>(headers, HttpStatus.FOUND);
//    }

}

















